package com.qmgyl.marketshop.product.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.qmfresh.service.common.dto.ListWithPage;
import com.qmfresh.service.common.utils.DateUtil;
import com.qmfresh.service.entity.ProductSsu;
import com.qmfresh.service.entity.ProductSsuPrice;
import com.qmfresh.service.entity.Sku;

import com.qmfresh.service.shop.facade.dto.ShopSsuQuery;
import com.qmgyl.marketshop.api.ProductServiceApi;

import com.qmfresh.service.product.facade.dto.ProductQuery;
import com.qmfresh.service.shop.facade.dto.ShopSkuQuery;
import com.qmfresh.service.shop.facade.dto.SkuBind;
import com.qmfresh.service.shop.facade.vo.ShopSkuResult;
import com.qmgyl.marketshop.api.ServiceApi;
import com.qmgyl.marketshop.vo.SkuVo;

import util.JsonUtil;
import util.Page;

@Controller
@RequestMapping(value = "/product")
public class ProductController {
	@Autowired
	private ServiceApi serviceApi;
	
	@Autowired
	private ProductServiceApi prodServApi;
	
	@RequestMapping(value = "/prodModifyPrice")
	public String prodModifyPrice(ModelMap model){
		return "product/prodModifyPrice";
	}
	
	@RequestMapping(value = "/ssuPriceList")
	public String ssuPriceList(ModelMap model){
		return "product/ssuPriceList";
	}
	
	@RequestMapping(value = "/skuExpt")
	public String index(ModelMap model){
		return "product/skuExpt";
	}
	
	@RequestMapping(value = "/list")
	public String list(ModelMap model){
		return "product/skuExpt";
	}
	
	@RequestMapping(value = "/skuList")
	public String skuList(ModelMap model){
		return "product/skuList";
	}
	
	@RequestMapping(value = "/bindSku")
	public void doBindSku(String id,HttpServletResponse response) throws IOException{
		SkuBind sb = new SkuBind();
		String[] ids = id.split(",");
		Set<Integer> idsets = new HashSet<Integer>();
		for (String i : ids) {
			idsets.add(Integer.parseInt(i));
		}
		sb.setSkuIds(idsets);
		boolean ret = serviceApi.bindSku(sb);
		Map<String,String> result = new HashMap<String,String>();
		if(ret) {
			result.put("code","0");
		}
		else {
			result.put("code","1");
		}
		//0成功，1失败
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(result));
	}
	
	@RequestMapping(value = "/unbindSkuList",method=RequestMethod.POST)
	public void unbindSkuList(HttpServletResponse response) throws IOException{
		ProductQuery pq = new ProductQuery();
		
		ListWithPage<Sku> skus = serviceApi.skuUnbindList(pq);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", skus.getTotalCount());
		List<SkuVo> list=new ArrayList<SkuVo>(skus.getListData().size());
		
		for (Sku sku : skus.getListData()) {
			SkuVo sv = new SkuVo();
			sv.setId(sku.getId());
			sv.setSkuCode(sku.getSkuCode());
			sv.setSkuDesc(sku.getSkuDesc());
			sv.setSkuFormat(sku.getSkuFormat());
			sv.setSkuName(sku.getSkuName());
			sv.setStatus(sku.getStatus());
			sv.setuT(new Date((long)sku.getUT()*1000));
			sv.setcT(new Date((long)sku.getCT()*1000));
			list.add(sv);
		}
		data.put("rows", list);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(data));
	}
	
	@RequestMapping(value = "/ssuConfig")
	public String ssuConfig(ModelMap model){
		return "product/ssuConfig";
	}
	@RequestMapping(value = "/ssuList")
	public String ssuList(ModelMap model){
		return "product/ssuList";
	}
	
	@RequestMapping(value="/{name}", method = RequestMethod.GET)
	public String data(@PathVariable("name") String name){
		return name;
	}
	
	@RequestMapping(value="/getList")
	@ResponseBody
	public void getList(HttpServletRequest req,HttpServletResponse res ) throws Exception{
		
		List<ProductSsu> list=new ArrayList<ProductSsu>();
		for(int i=0;i<10;i++){
			ProductSsu productSsu=new ProductSsu();
			productSsu.setSsuCode(i+"1212323");
			productSsu.setId(i);
			productSsu.setSkuId(i);
			productSsu.setSsuName(i+"ssuName");
			productSsu.setStatus(1);
			productSsu.setSsuFp(1);
			productSsu.setSsuUnit(1);
			productSsu.setSsuFormat(i+"�������");
			productSsu.setUT((int)(new Date().getTime()/1000));
			/*order.setCounstmer("wangxiaoming");
			order.setMoney("24");
			order.setOrderDate("2017-08-23");
			order.setOrderId("1212323");
			order.setOrderStatus("�ѷ���");
			order.setOrderId(i+"1212323");*/
			list.add(productSsu);
		}
		String currentPage = req.getParameter("page");
		String pageSize = req.getParameter("rows");
		System.out.println("page"+currentPage);
		System.out.println("pageSize"+pageSize);
		Page page=new Page();
		page.setResultList(list);
		page.setStart(1);
		page.setTotalSize(100);
		page.setPageSize(10);
		String json = JsonUtil.getJsonStringFromPage(page, "yyyy-MM-dd");
		res.setContentType("text/html;charset=UTF-8");
		res.getWriter().write(json);
	}
	
	/**
	 * 店仓ssu列表
	 * @param page
	 * @param rows
	 * @param start
	 * @param end
	 * @param status
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/getSsuList")
	@ResponseBody
	public void getSsuList(Integer page, Integer rows, Date start, Date end, Integer status,
			HttpServletResponse response) throws Exception{
		
		ShopSsuQuery shopSsuQuery = new ShopSsuQuery();
		shopSsuQuery.setPageSize(rows);
		shopSsuQuery.setPageIndex(page);
		DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
		DateTime s = DateTime.parse(DateTime.now().toString("yyyy-MM-dd"), format);
		if(start != null) {
			s = DateTime.parse(new DateTime(start).toString("yyyy-MM-dd"), format);
		}
		shopSsuQuery.setsTime((int) (s.toDate().getTime() / 1000));
		if(end != null) {
			DateTime e = DateTime.parse(new DateTime(end).toString("yyyy-MM-dd"), format);
			shopSsuQuery.seteTime((int) (e.toDate().getTime() / 1000));
		}
		
		
		ListWithPage<ProductSsu> pages = prodServApi.listProductSsu(shopSsuQuery);

		List<Object> list = new ArrayList<>();
		list.clear();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", pages.getTotalCount());
		List<ProductSsu> productSsus = new ArrayList<>(pages.getListData().size());
		for (ProductSsu productSsu : pages.getListData()) {
			
			productSsus.add(productSsu);
		}
		data.put("rows", productSsus);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(data));
	}
	
	@RequestMapping(value="/getSsuPriceList")
	@ResponseBody
	public void getSsuPriceList(Integer page, Integer rows, Date start, Date end, Integer status,
			HttpServletResponse response) throws Exception{
		ShopSsuQuery shopSsuQuery = new ShopSsuQuery();
		shopSsuQuery.setPageSize(rows);
		shopSsuQuery.setPageIndex(page);
		DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
		DateTime s = DateTime.parse(DateTime.now().toString("yyyy-MM-dd"), format);
		if(start != null) {
			s = DateTime.parse(new DateTime(start).toString("yyyy-MM-dd"), format);
		}
		shopSsuQuery.setsTime((int) (s.toDate().getTime() / 1000));
		if(end != null) {
			DateTime e = DateTime.parse(new DateTime(end).toString("yyyy-MM-dd"), format);
			shopSsuQuery.seteTime((int) (e.toDate().getTime() / 1000));
		}
		
		
		ListWithPage<ProductSsuPrice> pages = prodServApi.listSsuPrice(shopSsuQuery);

		List<Object> list = new ArrayList<>();
		list.clear();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", pages.getTotalCount());
		List<ProductSsuPrice> ProductSsuPriceList = new ArrayList<>(pages.getListData().size());
		for (ProductSsuPrice ssuPrice : pages.getListData()) {
			
			ProductSsuPriceList.add(ssuPrice);
		}
		data.put("rows", ProductSsuPriceList);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(data));
	}
	
	/**
	 * 商品改价
	 * @param productSsuPrice
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/modifyPrice")
	@ResponseBody
	public void modifyPrice(@ModelAttribute ProductSsuPrice productSsuPrice,
			HttpServletResponse response)throws IOException{
		productSsuPrice.setUT(DateUtil.getCurrentTimeIntValue());
		
		boolean ret = prodServApi.modifyPrice(productSsuPrice);
		Map<String,String> result = new HashMap<String,String>();
		if(ret) {
			result.put("code","1");
		}
		else {
			result.put("code","0");
		}
		//1成功，0失败
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(result));
	}
	
	@RequestMapping(value="/batchOnline")
	@ResponseBody
	public void batchOnline(@RequestBody ProductSsuPrice[] productSsuPrices,HttpServletResponse response)throws IOException{
		Map<String,String> result = new HashMap<String,String>();
		if(null!=productSsuPrices&&productSsuPrices.length>0){
			for(ProductSsuPrice productSsuPrice:productSsuPrices){
				productSsuPrice.setUT(DateUtil.getCurrentTimeIntValue());
			}
			boolean ret = prodServApi.batchOnline(productSsuPrices);
			
			if(ret) {
				result.put("code","1");
			}
			else {
				result.put("code","0");
			}
			
		}else{
			result.put("code","-1");
		}
		//1成功，0失败,-1异常
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(result));
		
	}
	
	@RequestMapping(value="/batchOffline")
	@ResponseBody
	public void batchOffline(@RequestBody ProductSsuPrice[] productSsuPrices,HttpServletResponse response)throws IOException{
		Map<String,String> result = new HashMap<String,String>();
		if(null!=productSsuPrices&&productSsuPrices.length>0){
			for(ProductSsuPrice productSsuPrice:productSsuPrices){
				productSsuPrice.setUT(DateUtil.getCurrentTimeIntValue());
			}
			boolean ret = prodServApi.batchOffline(productSsuPrices);
			
			if(ret) {
				result.put("code","1");
			}
			else {
				result.put("code","0");
			}
			
		}else{
			result.put("code","-1");
		}
		//1成功，0失败,-1异常
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(result));
	}
	
	/**
	 * 官方ssu列表
	 * @param page
	 * @param rows
	 * @param start
	 * @param end
	 * @param status
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/getProSsuList")
	@ResponseBody
	public void getProSsuList(Integer page, Integer rows, Date start, Date end, Integer status,
			HttpServletResponse response) throws Exception{
		
		ShopSsuQuery shopSsuQuery = new ShopSsuQuery();
		shopSsuQuery.setPageSize(rows);
		shopSsuQuery.setPageIndex(page);
		DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
		DateTime s = DateTime.parse(DateTime.now().toString("yyyy-MM-dd"), format);
		if(start != null) {
			s = DateTime.parse(new DateTime(start).toString("yyyy-MM-dd"), format);
		}
		shopSsuQuery.setsTime((int) (s.toDate().getTime() / 1000));
		if(end != null) {
			DateTime e = DateTime.parse(new DateTime(end).toString("yyyy-MM-dd"), format);
			shopSsuQuery.seteTime((int) (e.toDate().getTime() / 1000));
		}
		
		
		ListWithPage<ProductSsu> pages = prodServApi.listProSsu(shopSsuQuery);
		List<Object> list = new ArrayList<>();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", pages.getTotalCount());
		
		list.clear();
		List<ProductSsu> productSsus = new ArrayList<>(pages.getListData().size());
		if (null != pages && pages.getTotalCount() > 0) {
			for (ProductSsu productSsu : pages.getListData()) {

				productSsus.add(productSsu);
			}
		}
		data.put("rows", productSsus);
		
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(data));
	}
	
	@RequestMapping(value="/batchCopySsu")
	@ResponseBody
	public void batchCopySsu(@RequestBody ProductSsu[] productSsus,HttpServletResponse response)throws IOException{
		Map<String,String> result = new HashMap<String,String>();
		if(null!=productSsus&&productSsus.length>0){
			for(ProductSsu productSsu:productSsus){
				productSsu.setUT(DateUtil.getCurrentTimeIntValue());
			}
			boolean ret = prodServApi.batchCopySsu(productSsus);
			
			if(ret) {
				result.put("code","1");
			}
			else {
				result.put("code","0");
			}
			
		}else{
			result.put("code","-1");
		}
		//1成功，0失败,-1异常
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(result));
		
	}
	
	@RequestMapping(value="/getSkuList")
	@ResponseBody
	public void getSkuList(Integer rows,Integer page,Date start, Date end, Integer status,
			HttpServletRequest req,HttpServletResponse res ) throws Exception{
		ShopSkuQuery ssq = new ShopSkuQuery();
		ssq.setPageSize(rows);
		ssq.setPageIndex(page);
				
		ListWithPage<Sku> pages = serviceApi.skuBoundList(ssq);
		List<Sku> skuList = pages.getListData();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", pages.getTotalCount());
		/*List<Sku> list=new ArrayList<Sku>();
		for (ShopSkuResult ssr : ssrs.getListData()) {
			Sku sku=new Sku();
			sku.setClass1Id(ssr.getClass1Id());
			sku.setClass1Name(ssr.getClass1Name());
			sku.setId(ssr.getSkuId());
			//sku.setSkuCode(ssr.getSkuFormat());
			sku.setSkuFormat(ssr.getSkuFormat());
			sku.setSkuName(ssr.getSkuName());
			list.add(sku);
		}*/
//		
//		for(int i=0;i<10;i++){
//			
//			sku.setClass3Id(1);
//			sku.setId(i);
//			sku.setSkuCode(i+"1212323");
//			sku.setSkuDesc(i+"SkuDesc");
//			sku.setSkuName(i+"skuname");
//			sku.setSkuFormat(i+"skuFormat");
//			sku.setInternationalCode(i+"internationalCode");
//			sku.setUT((int)(new Date().getTime()/1000));
//			sku.setStatus(1);
//			list.add(sku);
//		}
		/*if(null!=req.getParameter("skuNo")&&!"".equals(req.getParameter("skuNo"))){
			String skuNo = req.getParameter("skuNo");
			for(int i = list.size() - 1; i >= 0; i--){
				if(!skuNo.equals(list.get(i).getSkuCode())){
					list.remove(i);
				}
			}
		}*/
		
		
//		String currentPage = req.getParameter("page");
//		String pageSize = req.getParameter("rows");
//		System.out.println("page"+currentPage);
//		System.out.println("pageSize"+pageSize);
//		Page page=new Page();
//		page.setResultList(list);
//		page.setStart(1);
//		page.setTotalSize(100);
//		page.setPageSize(10);
//		String json = JsonUtil.getJsonStringFromPage(page, "yyyy-MM-dd");
		data.put("rows", skuList);
		res.setContentType("application/json;charset=UTF-8");
		res.getWriter().write(JSONObject.toJSONString(data));
	}
	
	@RequestMapping(value="/getBindSkuList")
	@ResponseBody
	public void getBindSkuList(HttpServletRequest req,HttpServletResponse res ) throws Exception{
		
		List<Sku> list=new ArrayList<Sku>();
		for(int i=0;i<10;i++){
			Sku sku=new Sku();
			sku.setClass3Id(1);
			sku.setId(i);
			sku.setSkuCode(i+"1212323");
			sku.setSkuDesc(i+"SkuDesc");
			sku.setSkuName(i+"skuname");
			sku.setSkuFormat(i+"skuFormat");
			sku.setInternationalCode(i+"internationalCode");
			sku.setUT((int)(new Date().getTime()/1000));
			sku.setStatus(1);
			/*order.setCounstmer("wangxiaoming");
			order.setMoney("24");
			order.setOrderDate("2017-08-23");
			order.setOrderId("1212323");
			order.setOrderStatus("�ѷ���");
			order.setOrderId(i+"1212323");*/
			list.add(sku);
		}
		if(null!=req.getParameter("skuName")&&!"".equals(req.getParameter("skuName"))){
			String skuName = req.getParameter("skuName");
			for(int i = list.size() - 1; i >= 0; i--){
				if(!skuName.equals(list.get(i).getSkuName())){
					list.remove(i);
				}
			}
		}
		
		
		String currentPage = req.getParameter("page");
		String pageSize = req.getParameter("rows");
		System.out.println("page"+currentPage);
		System.out.println("pageSize"+pageSize);
		Page page=new Page();
		page.setResultList(list);
		page.setStart(1);
		page.setTotalSize(100);
		page.setPageSize(10);
		String json = JsonUtil.getJsonStringFromPage(page, "yyyy-MM-dd");
		res.setContentType("text/html;charset=UTF-8");
		res.getWriter().write(json);
	}
	
	@RequestMapping(value="/getProdSsuPriceList")
	@ResponseBody
	public void getProdSsuPriceList(HttpServletRequest req,HttpServletResponse res ) throws Exception{
		
		List<ProductSsuPrice> list=new ArrayList<ProductSsuPrice>();
		for(int i=0;i<10;i++){
			ProductSsuPrice prodSsuPrice=new ProductSsuPrice();
			prodSsuPrice.setId(Long.parseLong(i+""));
			prodSsuPrice.setPrice(Long.parseLong(i+""));
			prodSsuPrice.setSkuId(Long.parseLong(i+""));
			prodSsuPrice.setSsuId(Long.parseLong(i+""));
			prodSsuPrice.setUT((int)(new Date().getTime()/1000));
			prodSsuPrice.setIsStore(1);
			
			list.add(prodSsuPrice);
		}
		
		Integer isStore = Integer.parseInt(req.getParameter("isStore"));
		
		for(int i = list.size() - 1; i >= 0; i--){
			if(isStore!=list.get(i).getIsStore()){
				list.remove(i);
			}
		}
		
		String currentPage = req.getParameter("page");
		String pageSize = req.getParameter("rows");
		System.out.println("page"+currentPage);
		System.out.println("pageSize"+pageSize);
		Page page=new Page();
		page.setResultList(list);
		page.setStart(1);
		page.setTotalSize(100);
		page.setPageSize(10);
		String json = JsonUtil.getJsonStringFromPage(page, "yyyy-MM-dd");
		res.setContentType("text/html;charset=UTF-8");
		res.getWriter().write(json);
	}
	
	/**
	 * ����JSON����
	 * @param request
	 * @param response
	 */
	@RequestMapping("/productJson")
	public void json(Integer start,Integer length, HttpServletRequest request, HttpServletResponse response){
		
		
		
		List<Object> list = new ArrayList();
		list.clear();
		for(int i=start;i<start+10;i++){
			Map<String, Object> data = new HashMap<String, Object>();
			
			data.put("seq",i);
			data.put("cT", new Date());
			data.put("productClass", "��Ʒ"+i);// �̻�����
			data.put("status", 1);
			data.put("productCode", 20004+i);
			data.put("productName", "ǰ����(��/һ��/��Ƥ|��)"+i);
			data.put("productSsu", "1��/��");
			data.put("productCnt", 2);
			data.put("productPrice", "55.99");

			list.add(data);
		}
		
		Page pageObj = new Page(list,start%10,100,10);
		
		//ResponseJsonUtils.json(response, pageObj);
	}
	
	/**
	 * ����JSONP����
	 * @param callback JSONP�Ļص�����
	 * @param request
	 * @param response
	 */
	@RequestMapping("/productJsonp")
	public void json(String callback, HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> data = new HashMap<String, Object>();
		
		data.put("date", new Date());
		data.put("email", "accountwcx@qq.com");
		data.put("age", 30);
		data.put("name", "csdn");
		data.put("array", new int[]{1,2,3,4});
		
		if(callback == null || callback.length() == 0){
			//����clientû�з��ͻص���������ʹ��Ĭ�ϵĻص�����
			//ResponseJsonUtils.jsonp(response, data);
		}else{
			//ʹ��client�Ļص�����
			//ResponseJsonUtils.jsonp(response, callback, data);
		}
	}
	
	@RequestMapping(value = "/getProdByPage")  
    @ResponseBody  
    public String getCarrierByPage(HttpServletRequest request) throws Exception{  
        //ֱ�ӷ���ǰ̨  
        String draw = request.getParameter("draw");  
        //������ʼλ��  
        String startIndex = request.getParameter("startIndex");  
        //ÿҳ��ʾ������  
        String pageSize = request.getParameter("pageSize");  
        //��ȡ�����ֶ�  
        String orderColumn = request.getParameter("orderColumn");  
        if(orderColumn == null){  
            orderColumn = "carrier_id";  
        }  
        //��ȡ����ʽ  
        String orderDir = request.getParameter("orderDir");  
        if(orderDir == null){  
            orderDir = "asc";  
        }  
        //��ѯ����  
        String carrierId = request.getParameter("id");  
        String carrierName = request.getParameter("name");  
        String carrierStatus = request.getParameter("status");  
        
        int start = Integer.parseInt(startIndex);
        
        List<Object> list = new ArrayList<Object>();
		list.clear();
		for(int i=start;i<start+10;i++){
			Map<String, Object> data = new HashMap<String, Object>();
			
			data.put("prodNo",i);
			data.put("cT", new Date());
			data.put("prodName", "��Ʒ"+i);// �̻�����
			data.put("prodStatus", 1);
			data.put("prodUT", new Date());
			//data.put("productName", "ǰ����(��/һ��/��Ƥ|��)"+i);
			data.put("prodSku", "1��/��");
			//data.put("productCnt", 2);
			data.put("prodPrice", "55.99");

			list.add(data);
		}
		
		Map<Object, Object> info = new HashMap<Object, Object>();  
		
		info.put("pageData", list);  
        info.put("total", list.size());  
        info.put("draw", draw);

        //return JSONObject.toJSONString(info)+""; 
        return null;
    }  
}
